import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());

    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();

    const user = request.user;
    // console.log(roles, request.url, user);
    //console.log(await this.roleService.findId(user.userId));
    if (user.type === 'admin') {
      return true;
    }
    if (user.authority.find((item) => item.code === roles[0])) {
      return true;
    } else {
      throw new ForbiddenException('没有权限！');
    }
  }
}
